module namespace findmc = "http://www.xmlproject.com/smi/lib/controller/findmerchandising";

import module namespace http="http://www.28msec.com/modules/http";
import module namespace rest = "http://expath.org/ns/http-client";
import module namespace xqddf = "http://www.zorba-xquery.com/modules/xqddf";

declare namespace eBayNs="urn:ebay:apis:eBLBaseComponents";

declare collection findmc:entries as node()*;
declare variable $findmc:entries as xs:QName := xs:QName("findmc:entries");


declare sequential function findmc:search($title as xs:string, $query as xs:string)
{

    let $encodedTitle := 
        if ($title != "")
            then fn:encode-for-uri($title)
            else()
    let $ebayUrl := fn:concat("http://open.api.ebay.com/shopping?callname=FindPopularItems&amp;appid=AnthonyA-e5d4-4569-b305-0cc685ea12d3&amp;responseencoding=XML&amp;siteid=0&amp;QueryKeywords=", $encodedTitle, "&amp;AvailableItemsOnly=true&amp;MaxEntries=100&amp;version=745")    
    let $content := 
        if ($title != "")
            then findmc:addSearch(findmc:searchEbay($ebayUrl)[1])
        else()
    let $entries := findmc:list()
    let $lastEntry := $entries/entry[1]
    let $blocks := findmc:searchBlocks($lastEntry, $query)
    return
        $blocks
};

declare sequential function findmc:searchEbay($ebayUrl as xs:string)
{
    rest:send-request((), $ebayUrl)[2]
};

declare sequential function findmc:addSearch($searchResult)
{
  http:set-header("Cache-Control", "no-cache");
  xqddf:insert-nodes(
      $findmc:entries,
      <entry date="{fn:current-date()}" time="{fn:current-time()}">
        {$searchResult}
      </entry>
  );
};

declare sequential function findmc:list() {
  http:set-header("Cache-Control", "no-cache");
  
  let $entries := for $e in xqddf:collection($findmc:entries)
                  order by xs:date($e/@date), xs:time($e/@time)
                  return $e
  let $num_entries := fn:count($entries)
  return
    if($num_entries = 0)
    then    
      <p><b>No entries, yet.</b></p>
    else
      <entries>
      {
        for $entry at $pos in $entries[position() gt $num_entries - 1]
        let $numbering := if ($num_entries lt 5) then $pos else $num_entries - ( 1 - $pos) 
        return $entry
      }
      </entries>;
};

declare function findmc:searchBlocks($entry as element(entry), $query as xs:string)
{
    <blocks>
    {
    for $hit in $entry//eBayNs:Item[. contains text {$query} using stemming]
        let $title := $hit/eBayNs:Title/text()
        let $url := $hit/eBayNs:ViewItemURLForNaturalSearch/text()
        let $imageUrl := $hit/eBayNs:GalleryURL/text()
        let $price := $hit/eBayNs:ConvertedCurrentPrice/text()
                                
        return
            <block>
                <title>{$title}</title>
                <ebayUrl>{$url}</ebayUrl>
                <imgUrl>{$imageUrl}</imgUrl>
                <price>{$price}</price>               
            </block>
    }
    </blocks>
};